package com.hqyj.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.config.Sms;
import com.hqyj.pojo.R;
import com.hqyj.dao.UserInfoDao;
import com.hqyj.pojo.UserInfo;
import com.hqyj.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rock
 * @since 2022-10-27 10:24:35
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    //注入短信发送服务类
    @Autowired
    SmsClient smsClient;
    //注入短信pojo类
    @Autowired
    Sms sms;

    //注入邮件发送服务类
    @Autowired
    JavaMailSender javaMailSender;
    //读取发件人邮件
    @Value("${spring.mail.username}")
    private String sendEmail;

    //注入redis服务
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public R sendCode(String email) {
        try{
            //创建一个邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            //收件人
            message.setTo(email);
            //发件人
            message.setFrom(sendEmail);
            //标题
            message.setSubject("xxx网站的验证码");
            //邮件正文
            Random random = new Random();
            int code =random.nextInt(10000);
            message.setText("你的验证码是:"+code);
            //发送邮件
            javaMailSender.send(message);
            System.out.println("发送成功");
            //定义键名，保持唯一性
            String key ="code:"+email;
            //存入验证码，并设置有效时间为1分钟
            redisTemplate.opsForValue().set(key,code,1, TimeUnit.MINUTES);

            return R.ok("发送成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }

    }

    @Override
    public R codeValiede(UserInfo userInfo) {
        String key ="code:"+userInfo.getEmail();
        //判断验证码是否失效
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            return R.error("验证码已经失效");
        }else{
            if(userInfo.getCode().equals(obj+"")){
                return R.ok();
            }else{
                return R.error("验证码输入不正确");
            }

        }

    }

    @Override
    public R smsSendCode(String phone) throws TencentCloudSDKException, JsonProcessingException {
        //创建一个短信
        SendSmsRequest request = new SendSmsRequest();
        // 收信人手机号
        String[] p ={phone};
        request.setPhoneNumberSet(p);
        //短信内容
        Random random = new Random();
        String code =random.nextInt(10000)+"";
        String[] c ={code};
        request.setTemplateParamSet(c);
        //设置短信模板
        request.setTemplateId(sms.getSmsTemplateId());
        //设置短信SDK
        request.setSmsSdkAppId(sms.getSmsSdk());
        //设置短信签名
        request.setSignName(sms.getSmsName());

        //发送短信，获取响应信息
        SendSmsResponse response = smsClient.SendSms(request);
        //打印响应信息
        System.out.println(SendSmsResponse.toJsonString(response));

        ObjectMapper mapper = new ObjectMapper();
        //把响应信息转换成map
        Map<String,Object> map = mapper.readValue(SendSmsResponse.toJsonString(response), Map.class);
        ArrayList<LinkedHashMap<String,Object>> list = (ArrayList<LinkedHashMap<String,Object>> )map.get("SendStatusSet");
        if(list.get(0).get("Code").equals("Ok")){
            return R.ok();
        }
        return R.error();
    }
}
